<template>
  <div class="index">
    <h1>首页展示</h1>
    <div class="todo-input">
      <el-input v-model="inputValue" clearable></el-input>
      <el-button type="primary" @click="handleAdd">添加</el-button>
    </div>
    <todo-list :list="list" @remove="removeListItem" @update="updateListItem"></todo-list>
  </div>
</template>

<script>
import TodoList from "./components/TodoList";
import { mapGetters, mapActions } from "vuex";
import { Message, MessageBox } from "element-ui";

export default {
  name: "index",
  data() {
    return {
      inputValue: ""
    };
  },
  computed: {
    ...mapGetters("list", ["list"])
  },
  components: {
    TodoList
  },
  methods: {
    ...mapActions("list", ["addList", "removeList", "updateList"]),
    // 添加
    handleAdd() {
      // 查找数组中是否已经存在
      if (this.list.indexOf(this.inputValue) === -1) {
        if (this.inputValue) {
          this.addList(this.inputValue);
          this.inputValue = "";
        } else {
          Message({
            showClose: true,
            message: "请输入类容",
            type: "warning"
          });
        }
      } else {
        Message({
          showClose: true,
          message: "添加类容已存在",
          type: "warning"
        });
      }
    },
    // 删除
    removeListItem(index) {
      this.removeList(index);
    },
    // 修改
    updateListItem(index) {
      let _this = this;
      MessageBox.prompt("请输入类容", "修改", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入类容",
        inputValue: _this.list[index],
        inputPattern: /\S/,
        inputErrorMessage: "请输入类容"
      }).then(({ value }) => {
        if(_this.list.indexOf(value) !== -1){
          Message({
            showClose: true,
            message: "添加类容已存在",
            type: "warning"
          });
        }else if (_this.list[index] !== value){
          _this.updateList({index, data:value});
          return false;
        }
      }).catch(() => {
        
      });
    }
  }
};
</script>

<style lang="less" scoped>
.index {
  width: 800px;
  margin: 0 auto;

  h1 {
    font-size: 16px;
    color: #908686;
    font-family: "微软雅黑";
    text-align: center;
    margin: 20px 0;
  }

  img {
    width: 200px;
  }

  .todo-input {
    .el-input {
      width: 90%;
    }
  }
}
</style>

